extends State


## 玩家向指定方向快速移动距离，移动期间玩家处于无敌状态


@export var distance: float = 64
@export var afterimage_interval: float = 0.01

@onready var op_player_afterimage: ObjectPool = $OP_PlayerAfterimage


var _player: Player
var _original_pos: Vector2
var _direction: Vector2
var _dashing: bool
var _has_collision: bool

var _create_afterimage_last_time: int


func _ready() -> void:
    _player = _root.target


func _enter() -> void:
    _dashing = true
    _has_collision = false
    _original_pos = _player.center_position()
    _direction = _player.center_position().direction_to(_player.get_global_mouse_position())
    _player.is_invincibility = true
    # 冲刺次数减少
    _player.data.dash_count.add_modifier(-1)


func _exit() -> void:
    _player.is_invincibility = false


func _update(_delta: float) -> void:
    _player.velocity = _direction * _player.data.speed.value * 5

    _create_afterimage()

    if _original_pos.distance_squared_to(_player.center_position()) > distance ** 2 or _has_collision:
        _dashing = false
        _player.velocity = Vector2.ZERO

    
    if _dashing: return
    if _player.velocity.is_zero_approx():
        switch.emit("Idle")
    elif not Utils.get_input_vec2().is_zero_approx():
        switch.emit("Move")


func _fixed_update(delta: float) -> void:
    var collision := _player.move_and_collide(_player.velocity * delta)
    _has_collision = true if collision else false


func _create_afterimage() -> void:
    if Time.get_ticks_msec() - _create_afterimage_last_time > afterimage_interval * 1000:
        var player_afterimage := op_player_afterimage.acquire() as Afterimage
        var player_sprite := _player.sprite
        player_afterimage.setup(player_sprite.texture, player_sprite.global_position,
                            player_sprite.flip_h, player_sprite.flip_v,
                            Vector2i(player_sprite.hframes, player_sprite.vframes), player_sprite.frame,
                            player_sprite.region_enabled, player_sprite.region_rect)
        _create_afterimage_last_time = Time.get_ticks_msec()
        await player_afterimage.amt_player.animation_finished
        op_player_afterimage.release(player_afterimage)
